#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"

int main(int argc, char **argv)
{
	MPI_Status status;
	int rank, procnum, base;
	long   MAX_NUM, range;
	char *endptr;
	if(argc<2)
	{
		printf("USAGE: %s num\n",argv[0]);
		exit(0);
	}
	  
          //MAX_NUM = strtol(argv[1],&endptr);
          MAX_NUM = atoi(argv[1]);

	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD,&procnum);
	MPI_Comm_rank(MPI_COMM_WORLD,&rank);
	  range = MAX_NUM/(procnum-1);

if(rank!=0)
{
int result=0;
int a = (rank*range-range)+1;
int b = ((rank==(procnum-1))?MAX_NUM:rank*range);
int i;
	 for(i=a;i<=b;i++)
	 {
	  result+=i; 
	 }
//MPI_Bcast(num,1, MPI_LONG,,MPI_COMM_WORLD);
printf("rank %d result %d  for range a=%d   b=%d\n",rank,result,a,b);
MPI_Send(&result,1,MPI_INT,0,0,MPI_COMM_WORLD);

}
//printf("range %d MAX_NUM %d procnum %d \n",range,MAX_NUM,procnum);
int res=0,get=0,i;
/*
for(i=1;i<procnum;i++)
{
MPI_Recv(&get,1,MPI_INT,i,MPI_ANY_TAG,MPI_COMM_WORLD,&status);
res+=get;
}*/
int sum_array[procnum-1];
//int *rbuf;
//rbuf = (int *)malloc(procnum*(procnum-1)*sizeof(int));
//MPI_Gather(sum_array,(procnum-1),MPI_INT,rbuf,(procnum-1),MPI_INT,0,MPI_COMM_WORLD);
MPI_Reduce(&get,&res,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);

printf("result %d \n",res);

	MPI_Finalize();
//	exit(0);
return 0;
}
